package com.example.librarymanagementproject2.Common.aop;

import com.example.librarymanagementproject2.Common.config.RabbitConfig;
import com.example.librarymanagementproject2.Common.message.UserOperationMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @ClassName UserAspect
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/27 10:47
 * @Version 1.0
 */
@Aspect
@Component
public class UserAspect {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @author: kx
     * @date: 2025/10/27 10:53
     * @param joinPoint : 切入点
     * @description: 用户修改信息后置通知
    */
    @AfterReturning(value = "execution(* com.example.librarymanagementproject2.service.impl.UserServiceImpl.update*(..)) ||" +
                            "execution(* com.example.librarymanagementproject2.service.impl.UserServiceImpl.cancel*(..))")
    public void sendUserOperationMessage(JoinPoint joinPoint) {
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取参数
        Object[] args = joinPoint.getArgs();
        Long userId;

        switch (methodName) {
            // 修改头像
            case "updateAvatar":
                userId = (Long) args[0];
                break;
            // 注销账号
            case "cancelAccount":
                userId = (Long) args[0];
                break;
            default:
                return;
        }

        // 构建统一消息体
        UserOperationMessage userOperationMessage = new UserOperationMessage();
        userOperationMessage.setId(userId);
        userOperationMessage.setOperationType(methodName);

        // 创建消息唯一ID
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        // 投递消息
        rabbitTemplate.convertAndSend(RabbitConfig.USER_EXCHANGE, RabbitConfig.USER_OPERATION_ROUTING_KEY, userOperationMessage, correlationData);
    }
}
